package me.hetong.tool;

import java.math.BigInteger;

/**
 * 62进制工具类
 */
public class TtBase62Tool {

    private static final String BASE62 = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
    private static final int LENGTH = BASE62.length();

    public static String hexToBase62(String s) {
        // 将16进制字符串转换为字节数组
        byte[] bytes = hexStringToByteArray(s);
        // 将字节数组转换为BigInteger
        BigInteger number = new BigInteger(1, bytes); // 1表示正数
        StringBuilder sb = new StringBuilder();
        BigInteger base = BigInteger.valueOf(LENGTH);
        while (number.compareTo(BigInteger.ZERO) > 0) {
            BigInteger[] divmod = number.divideAndRemainder(base);
            sb.append(BASE62.charAt(divmod[1].intValue()));
            number = divmod[0];
        }
        return sb.reverse().toString();
    }

    private static byte[] hexStringToByteArray(String hex) {
        int len = hex.length();
        byte[] data = new byte[len / 2];
        for (int i = 0; i < len; i += 2) {
            data[i / 2] = (byte) ((Character.digit(hex.charAt(i), 16) << 4)
                    + Character.digit(hex.charAt(i + 1), 16));
        }
        return data;
    }

    public static void main(String[] args) {
//        for (int i = 0; i < 20; i++) {
//            String s = IdUtil.fastSimpleUUID();
//            String base62 = hexToBase62(s);
//            System.out.println("16进制: " + s);
//            System.out.println("62进制: " + base62);
//            System.out.println("长度变化: " + s.length() + " -> " + base62.length());
//        }
        System.out.println(hexToBase62("2c20e8f88b2f0ec369c03aeedb2452ef"));
    }

}
